package com.example.payment.service.impl;

import cn.hutool.core.util.IdUtil;
import com.example.payment.service.HystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class HystrixServiceImpl implements HystrixService {

    @Override
    public String success() {
        return "Thread " + Thread.currentThread().getName() + " success";
    }

    @Override
    @HystrixCommand(fallbackMethod = "timeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "200")})
    public String timeout() {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Thread " + Thread.currentThread().getName() + " timeout";
    }

    @Override
    @HystrixCommand(fallbackMethod = "circuitBreakerHandler", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),  //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), //失败率达到多少后跳闸
    })
    public String circuitBreaker(Long id) {
        if (id < 0) {
            throw new RuntimeException("Id cannot be negative");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName() + ", serial number：" + serialNumber;

    }

    public String timeoutHandler() {
        return "Service Payment System is busy, please try again later";
    }

    public String circuitBreakerHandler(Long id) {
        return "Id cannot be negative, id: " + id;
    }
}
